# todo 使用mixins 代替 逻辑性更强
import datetime
from exts import db
from common import constant
from sqlalchemy.orm import declared_attr
from common.constant import OrderStatus
from common import errors
from app.file.model import FileRelation


# ------------ 单据 -------------

class OrderModelMixin(object):
    """订单模型混入类"""
    id = db.Column(db.Integer, primary_key=True)

    order_sn = db.Column(db.String(constant.MIDDLE_DB_STR_LEN))
    # 单据日期
    date = db.Column(db.Date, default=datetime.datetime.utcnow)
    status = db.Column(db.String(constant.MIDDLE_DB_STR_LEN), default=constant.OrderStatus.DRAFT, nullable=False)
    draft_status = db.Column(db.String(constant.MIDDLE_DB_STR_LEN), default=constant.OrderDraftStatus.PENDING,
                             nullable=False)

    def check_draft_status(self):
        if self.status != OrderStatus.DRAFT:
            raise errors.BadRequestError('无法保存草稿，这不是一个草稿单！')

    def update_images_by_belong_type(self, image_ids, belong_type):
        if image_ids or len(image_ids) == 0:
            # 删除旧的
            old_relations = FileRelation.query.filter_by(
                belong_id=self.id,
                belong_type=belong_type).all()
            for old_relation in old_relations:
                old_relation.hard_delete()
            # 创建新的
            for image_id in image_ids:
                FileRelation.create(
                    file_id=image_id, belong_id=self.id,
                    belong_type=belong_type)

    @classmethod
    def generate_order_sn(cls, prefix):
        today = datetime.date.today().strftime('%Y%m%d')
        # 今天的第一个单据是否已存在
        last_order = cls.query.filter(cls.order_sn.like(prefix + today + '%')).order_by(cls.id.desc()).first()
        if last_order:
            last_order_sn = last_order.order_sn
            serial_number = int(last_order_sn[-4:]) + 1
        else:
            serial_number = 1
        order_sn = prefix + today + str(serial_number).zfill(4)
        return order_sn
# class PurchaseSaleOrderModelMixin(object):
#     @declared_attr
#     def customer_id(cls):
#         return db.Column(db.Integer, db.ForeignKey('customer_id.id'))
#
#     @declared_attr
#     def warehouse_id(cls):
#         return db.Column(db.Integer, db.ForeignKey('warehouse_id.id'))
#
#     # @declared_attr
#     # def account_id(cls):
#     #     return db.Column(db.Integer, db.ForeignKey('account_id.id'))
#     #
#     # @declared_attr
#     # def second_account_id(cls):
#     #     return db.Column(db.Integer, db.ForeignKey('second_account_id.id'))
#
#     # 快递单号
#     tracking_number = db.Column(db.String(constant.LONG_DB_STR_LEN))
#     # 是否已开票
#     is_make = db.Column(db.Boolean, default=False, server_default="False")
#     bill_info = db.Column(db.String(constant.LONG_DB_STR_LEN))
#
#     # # relation
#     # customer = db.relationship('Customer')
#     # warehouse = db.relationship("Warehouse")
#     # account = db.relationship("Account", foreign_keys='Order.account_id')
#     # second_account = db.relationship("Account", foreign_keys='Order.second_account_id')
#
#
# class ReturnOrderMixin(object):
#     related_order_id = db.Column(db.Integer, db.ForeignKey('purchase_order.id'))
#     order_skus = db.relationship("PurchaseReturnOrderSku", back_populates='order', cascade="all, delete, delete-orphan")
#
#
# class TransferOrderMixin(object):
#     from_warehouse_id = db.Column(db.Integer, db.ForeignKey('warehouse.id'))
#     to_warehouse_id = db.Column(db.Integer, db.ForeignKey('warehouse.id'))

# ------------ 单据商品详情 -------------
